﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- 常用搜索条件 -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="Name_FormItem" prop="Name">
							<template #label>
								<WtmLabelTooltip label="姓名" tooltip="员工姓名" />
							</template>
							<el-input v-model="searchData.Name" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="StaffNo_FormItem" prop="StaffNo">
							<template #label>
								<WtmLabelTooltip label="工号" tooltip="员工工号" />
							</template>
							<el-input v-model="searchData.StaffNo" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="Phone_FormItem" prop="Phone">
							<template #label>
								<WtmLabelTooltip label="手机号" tooltip="手机号码" />
							</template>
							<el-input v-model="searchData.Phone" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="BillCode_FormItem" prop="BillCode">
							<template #label>
								<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
							</template>
							<el-input v-model="searchData.BillCode" clearable></el-input>
						</el-form-item>
					</el-col>

					<!-- 可展开的详细搜索条件 -->
					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="BillStatus_FormItem" prop="BillStatus">
								<template #label>
									<WtmLabelTooltip label="单据状态" tooltip="单据状态" />
								</template>
								<el-select v-model="searchData.BillStatus" clearable>
									<el-option key="草稿" value="草稿" label="草稿"></el-option>
									<el-option key="正文" value="正文" label="正文"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="WorkflowStatus_FormItem" prop="WorkflowStatus">
								<template #label>
									<WtmLabelTooltip label="工作流状态" tooltip="工作流状态" />
								</template>
								<el-select v-model="searchData.WorkflowStatus" clearable>
									<el-option key="待提交" value="待提交" label="待提交"></el-option>
									<el-option key="提交中" value="提交中" label="提交中"></el-option>
									<el-option key="审核中" value="审核中" label="审核中"></el-option>
									<el-option key="已完成" value="已完成" label="已完成"></el-option>
									<el-option key="已取消" value="已取消" label="已取消"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="ApprovalTime_FormItem" prop="ApprovalTime">
								<template #label>
									<WtmLabelTooltip label="审批时间" tooltip="审批时间" />
								</template>
								<el-date-picker type="daterange" v-model="searchData.ApprovalTime" clearable></el-date-picker>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysHrProbationRequestBill/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysHrProbationRequestBill/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysHrProbationRequestBill/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysHrProbationRequestBill/SysHrProbationRequestBillExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>

		<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
			<template #operation>
				<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
					<template v-slot="scope">
						<div class="operation-container">
							<WtmButton
								v-auth="'/api/SysHrProbationRequestBill/Edit'"
								v-if="scope.row.BillStatus === BILL_STATUS.DRAFT"
								:is-text="true"
								icon="fa fa-pencil-square"
								type="warning"
								:button-text="$t('message._system.common.vm.edit')"
								@click="OnEditRowClick(scope.row)"
							/>
							<WtmButton
								v-if="scope.row.CanApprove == 'true'"
								:is-text="true"
								icon="-o"
								type="warning"
								button-text="审批"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-else
								v-auth="'/api/SysHrProbationRequestBill/{id}'"
								:is-text="true"
								icon="fa fa-info-circle"
								type="info"
								:button-text="$t('message._system.common.vm.detail')"
								@click="OnDetailsRowClick(scope.row)"
							/>
							<WtmButton
								v-auth="'/api/SysHrProbationRequestBill/BatchDelete'"
								v-if="scope.row.BillStatus === BILL_STATUS.DRAFT"
								icon="fa fa-trash"
								type="danger"
								:button-text="$t('message._system.common.vm.delete')"
								:confirm="$t('message._system.common.vm.deletetip')"
								:is-text="true"
								@click="onDelete(scope.row)"
							/>
						</div>
					</template>
				</el-table-column>
			</template>
		</WtmTable>
	</div>
</template>

<script setup lang="ts" name="转正申请;true;HengTong.Areas.Hr.Controllers;SysHrProbationRequestBill">
import ElMessage from 'element-plus/es/components/message/index';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed } from 'vue';
import { SysHrProbationRequestBillApi as api } from '/@/views/hr/syshrprobationrequestbill/api';
import { ISysHrProbationRequestBillView, ISysHrProbationRequestBillQuery } from '/@/views/hr/syshrprobationrequestbill/api/interface';
import other from '/@/utils/other';
import request from '/@/utils/request';

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
	FORMAL: '正文',
} as const;

const API_ENDPOINTS = {
	ORGS: '/api/SysHrProbationRequestBill/GetSysOrgs',
	JOB_POSITIONS: '/api/SysHrProbationRequestBill/GetSysJobPositions',
} as const;

const ci = getCurrentInstance() as any;
const loading = ref(false);
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysHrProbationRequestBillQuery;
		/** 主表ID */
		entityId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
	}
);

const stateData = reactive({
	AllSysOrgs: [] as any[],
	AllSysGroups: [] as any[],
	AllSysJobPositions: [] as any[],
});

const searchData = ref<ISysHrProbationRequestBillQuery>({});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）
	data: [],
	// 表头内容（必传，注意格式）
	header: [
		{ title: '单据编号', key: 'BillCode', type: 'text', isCheck: true },
		{ title: '单据状态', key: 'BillStatus', type: 'text', isCheck: true },
		{
			title: '工作流状态',
			key: 'WorkflowStatus',
			type: 'tag',
			isCheck: true,
			tagType: (row: ISysHrProbationRequestBillView) => {
				const statusMap: Record<string, string> = {
					待提交: 'info',
					提交中: 'info',
					审核中: 'warning',
					已完成: 'success',
					已取消: 'danger',
				};
				return statusMap[row.WorkflowStatus || ''] || 'info';
			},
		},
		{ title: '姓名', key: 'Name', type: 'text', isCheck: true },
		{ title: '工号', key: 'StaffNo', type: 'text', isCheck: true },
		{ title: '转正后工号', key: 'RegularStaffNo', type: 'text', isCheck: true },
		{ title: '公司', key: 'OrgName', type: 'text', isCheck: true },
		{ title: '手机号', key: 'Phone', type: 'text', isCheck: true },
		{ title: '入职日期', key: 'EntryDate', type: 'text', isCheck: true },
		{ title: '转正日期', key: 'RegDate', type: 'text', isCheck: true },
		{ title: '试用期起始日期', key: 'ProbationStartDate', type: 'text', isCheck: true },
		{ title: '试用期结束日期', key: 'ProbationEndDate', type: 'text', isCheck: true },
		// { title: '试用期薪资', key: 'ProbationSalary', type: 'text', isCheck: true },
		// { title: '转正后薪资', key: 'RegularSalary', type: 'text', isCheck: true },
		{ title: '试用期工作内容', key: 'JobContent', type: 'text', isCheck: true },
		{ title: '试用期工作成果', key: 'JobAchievements', type: 'text', isCheck: true },
		{ title: '转正意见', key: 'RegOpinion', type: 'text', isCheck: true },
		{ title: '其他说明', key: 'Remarks', type: 'text', isCheck: true },
		{ title: '审批人', key: 'Approver', type: 'text', isCheck: true },
		{ title: '审批时间', key: 'ApprovalTime', type: 'text', isCheck: true },
		{ title: '备注', key: 'Remark', type: 'text', isCheck: true },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});
// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		other.setFormError(ci, error);
	}
};
const OnCreateClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, null, getTableData);
};

const OnEditRowClick = (row: ISysHrProbationRequestBillView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData);
};

const OnDetailsRowClick = (row: ISysHrProbationRequestBillView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData);
};

// 删除
const onDelete = (row: ISysHrProbationRequestBillView) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysHrProbationRequestBillView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};

// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 加载页面数据
const loadPageData = async () => {
	const [orgs, jobPositions] = await Promise.allSettled([
		other.getSelectList(API_ENDPOINTS.ORGS, [], false),
		other.getSelectList(API_ENDPOINTS.JOB_POSITIONS, [], false),
	]);

	// 处理结果
	if (orgs.status === 'fulfilled') stateData.AllSysOrgs = orgs.value;
	if (jobPositions.status === 'fulfilled') stateData.AllSysJobPositions = jobPositions.value;

	// 加载表格数据
	await getTableData();
};

// 页面加载时
onMounted(async () => {
	loading.value = true;

	try {
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
	}
});
</script>
